<template>
  <div>
    <el-form label-width="90px" label-position="right">
      <el-row :gutter="30">
        <el-col :span="24">
          <el-form-item label="当前节点：">
            <el-cascader
              :options="treeOption"
              v-model="selectedOptions"
              style="width:63%"
              placeholder="选择人员节点"
              change-on-select
              @change="selectedOptionsChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="8">
          <el-form-item label="人员姓名：">
            <el-input v-model="searchData.username" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="日期选择：">
            <el-date-picker
              v-model="searchData.time1"
              :picker-options="pickerOptions0"
              type="date"
              placeholder="开始日期"/>
            <el-date-picker
              v-model="searchData.time2"
              :picker-options="pickerOptions1"
              type="date"
              placeholder="结束日期"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-search" @click="doFilter">搜索</el-button>
        </el-col>
        <!-- <el-col :span="4">
          <el-button type="primary" @click="dialogAddVisible = true" icon="el-icon-plus">添加人员</el-button>
        </el-col> -->
      </el-row>
    </el-form>

    <!--展示区域-->
    <el-table
      v-loading="loading"
      :data="attendanceList"
      max-height="900px"
      border
      fit
      highlight-current-row>
      <el-table-column
        align="center"
        prop="name"
        label="姓名"
        fixed
        width="100">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) of dateList"
        :key="index"
        :label="item"
        align="center"
        prop="list"
        width="240"
      >
        <template slot-scope="scope">
          <div class="time-line">
            <div v-for="(listItem, index) in scope.row.list[item]" :key="index" class="time-line-div">
              <p>{{ listItem.time }}</p>
              <p ref="circular"/>
              <p>{{ listItem.desc }}</p>
              <p class="line-top"/>
            </div>
          </div>
        </template>

    </el-table-column></el-table>
  </div>
</template>

<script>
import { getCommunityAll, getChuru } from '@/api/table'
import { getPermission, getRid } from '@/utils/auth'
export default {
  name: 'WorkAttendance',
  data() {
    return {
      loading: true,
      treeOption: [],
      selectedOptions: [],
      treeArray: [],
      searchData: {
        username: '',
        time1: '',
        time2: ''
      },
      pickerOptions0: {
        disabledDate: (time) => {
          if (this.searchData.time2 !== '' && this.searchData.time2 !== null) {
            const currentTime = this.searchData.time2
            const threeMonths = currentTime.setMonth(currentTime.getMonth() - 1)
            currentTime.setMonth(currentTime.getMonth() + 1)
            return time.getTime() > this.searchData.time2 || time.getTime() < threeMonths
          } else {
            return time.getTime() > Date.now()
          }
        }
      },
      pickerOptions1: {
        disabledDate: (time) => {
          if (this.searchData.time1 !== '' && this.searchData.time1 !== null) {
            const currentTime = this.searchData.time1
            const threeMonths = currentTime.setMonth(currentTime.getMonth() + 1)
            currentTime.setMonth(currentTime.getMonth() - 1)
            return time.getTime() < this.searchData.time1 || time.getTime() > threeMonths
          } else {
            return time.getTime() > Date.now()
          }
        }
      },
      attendanceList: [],
      dateList: [],
      dateTimeStamp: {
        startTime: '',
        endTime: ''
      }
    }
  },
  created() {
    var rid = getRid()
    if (getPermission() === 'root' && rid === '0') {
      this.$router.push({ path: '/admin' })
    } else {
      this.getTreeData()
    }
  },
  methods: {
    // 获取当前树形结构，并选中当前节点
    getTreeData() {
      getCommunityAll().then(response => {
        var data = response
        this.treeArray = JSON.parse(JSON.stringify(data))
        var node_id = getRid()
        if (node_id !== 'undefined') {
          this.treeOption = this.filterArray(data, node_id)
        } else {
          this.treeOption = this.filterArray(data)
        }
        this.selectedOptions = [this.treeOption[0].value]
        // 获取当前日期，dateList值为前7天
        this.handleDateList()
        // 根据nodeid和时间查询出入信息渲染表格
        var jsonData = {
          nodeid: {
            $in: [this.treeOption[0].value]
          },
          datetime: {
            $gte: this.dateTimeStamp.startTime.toString(),
            $lt: this.dateTimeStamp.endTime.toString()
          }
        }
        this.fetchData(jsonData)
      })
    },
    // 构建节点数组
    filterArray(data, pid) {
      var tree = []
      var temp
      for (var i = 0; i < data.length; i++) {
        if (data[i].pid === pid) {
          var obj = data[i]
          obj.value = obj._id
          obj.label = obj.name
          temp = this.filterArray(data, data[i]._id)
          if (temp.length > 0) {
            obj.children = temp
          }
          tree.push(obj)
        }
      }
      return tree
    },
    // 切换节点，重新获取出入表数据，渲染表格
    selectedOptionsChange(value) {
      var node_id = value[value.length - 1]
      var data = {
        nodeid: {
          $in: [node_id]
        },
        datetime: {
          $gte: this.dateTimeStamp.startTime.toString(),
          $lt: this.dateTimeStamp.endTime.toString()
        }
      }
      this.fetchData(data)
    },
    // 搜索逻辑（姓名和日期）
    doFilter() {
      var data = this.searchData

      var jsonData = {
        nodeid: {
          $in: [this.selectedOptions[this.selectedOptions.length - 1]]
        },
        datetime: {
          $gte: this.dateTimeStamp.startTime.toString(),
          $lt: this.dateTimeStamp.endTime.toString()
        }
      }
      if (data.username) {
        jsonData['username'] = data.username
      }
      if (data.time1 && data.time2) {
        jsonData['datetime'] = {
          $gte: data.time1.getTime().toString(),
          $lt: (data.time2.getTime() + 24 * 60 * 60 * 1000 - 1).toString()
        }
      }
      // 处理dateList，更新表头
      var dates = []
      var start = this.getDateStr(0, this.searchData.time1)
      var end = this.getDateStr(0, this.searchData.time2)
      var days = this.DateDiff(start.slice(0, start.indexOf(' ')), end.slice(0, end.indexOf(' ')))
      for (let i = days; i > -1; i--) {
        dates.push(this.getDateStr(i, this.searchData.time2))
      }
      this.dateList = dates.reverse()
      this.fetchData(jsonData)
    },
    // 处理日期数组，展示表头
    handleDateList() {
      var arr = []
      for (let i = 6; i > -1; i--) {
        arr.push(this.getDateStr(i))
      }
      this.dateList = arr.reverse()
      this.dateTimeStamp.startTime = Date.parse(arr[arr.length - 1].slice(0, arr[arr.length - 1].indexOf(' ')) + ' 00:00:00')
      this.dateTimeStamp.endTime = Date.parse(arr[0].slice(0, arr[0].indexOf(' ')) + ' 23:59:59')
    },
    // 格式化日期
    getDateStr(day, date, timeStamp) {
      var today = new Date()
      var itoday = new Date()
      if (date) {
        today = new Date(Date.parse(date))
      }
      if (timeStamp) {
        itoday.setTime(timeStamp)
      } else {
        var targetday_milliseconds = today.getTime() - 1000 * 60 * 60 * 24 * day
        itoday.setTime(targetday_milliseconds)
      }
      var tYear = itoday.getFullYear()
      var tMonth = itoday.getMonth()
      var tDate = itoday.getDate()
      tMonth = this.doHandleMonth(tMonth + 1)
      tDate = this.doHandleMonth(tDate)
      var weekNumber = this.getWeekNumber(tYear, tMonth, tDate)
      var myddy = itoday.getDay()
      var weekday = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      myddy = weekday[myddy]
      if (timeStamp) {

        var thours = itoday.getHours()
        var tminutes = itoday.getMinutes()
        var tseconds = itoday.getSeconds()
        return tYear + '-' + tMonth + '-' + tDate + '  ' + thours + ':' + tminutes + ':' + tseconds
      } else {
        return tYear + '-' + tMonth + '-' + tDate + ' 第' + weekNumber + '周' + ' ' + myddy
      }
    },

    // 月份/日期/时间为个位数时，加0

    doHandleMonth(month) {
      var m = month
      if (month.toString().length === 1) {
        m = '0' + month
      }
      return m
    },
    // 判断是否为闰年
    isLeapYear(year) {
      return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)
    },
    // 获取某一年份的某一月份的天数
    getMonthDays(year, month) {
      return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (this.isLeapYear(year) ? 29 : 28)
    },
    // 获取当前日期为第几周
    getWeekNumber(y, m, d) {
      var now = new Date(y, m - 1, d)
      var year = now.getFullYear()
      var month = now.getMonth()
      var days = now.getDate()
      // 那一天是那一年中的第多少天
      for (var i = 0; i < month; i++) {
        days += this.getMonthDays(year, i)
      }

      // 那一年第一天是星期几
      var yearFirstDay = new Date(year, 0, 1).getDay() || 7
      var week = null
      if (yearFirstDay == 1) {
        week = Math.ceil(days / yearFirstDay)
      } else {
        days -= (7 - yearFirstDay + 1)
        week = Math.ceil(days / 7) + 1
      }
      return week
    },
    // 考勤---日期间隔
    DateDiff(sDate1, sDate2) {
      var oDate1, oDate2, iDays
      oDate1 = new Date(sDate1)
      oDate2 = new Date(sDate2)
      iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24)
      return iDays
    },
    // 获取出入表数据
    fetchData(data) {
      getChuru(data).then(response => {
        var resultObj = {
          'name': '',
          'list': {}
        }
        var resultArr = []
        var uidArr = []
        if (response.length) {
          this.dateList.forEach((dateItem) => {
            var newdateItem = dateItem.slice(0, dateItem.indexOf(' '))
            resultObj.list[dateItem] = []
            response.forEach((item, index) => {
              if (!item.delete) {
                var date = this.getDateStr(0, null, item.datetime)
                if (!uidArr.includes(item.uid)) {
                  uidArr.push(item.uid)
                  resultObj.name = item.username
                  if (date.slice(0, date.indexOf(' ')) === newdateItem) {
                    item.time = this.doHandleMonth(new Date(Number(item.datetime)).getHours()) + ':' + this.doHandleMonth(new Date(Number(item.datetime)).getMinutes()) + ':' + this.doHandleMonth(new Date(Number(item.datetime)).getSeconds())
                    item.desc = item.addplace + ' ' + item.addCamera + '号摄像头 ' + item.direction
                    resultObj.list[dateItem].push(item)
                  }
                  resultArr.push(resultObj)
                } else {

                  if (date.slice(0, date.indexOf(' ')) === newdateItem) {
                    item.time = this.doHandleMonth(new Date(Number(item.datetime)).getHours()) + ':' + this.doHandleMonth(new Date(Number(item.datetime)).getMinutes()) + ':' + this.doHandleMonth(new Date(Number(item.datetime)).getSeconds())
                    item.desc = item.addplace + ' ' + item.addCamera + '号摄像头 ' + item.direction
                    resultArr[uidArr.indexOf(item.uid)].list[dateItem].push(item)
                  }
                }
              }
            })
          })
        }
        this.attendanceList = resultArr
      })
      this.loading = false
    }
  }
}
</script>

<style>
  .time-line{
    position: relative;
    width:100%;
    height: 260px;
    margin:0 auto;
    overflow-y: auto;
  }
  .time-line-div{
    position:relative;
    min-height:65px;
    white-space: normal;
  }
  .time-line-div>p:nth-child(1){
    position: absolute;
    top: 7px;
    left:-10px;
    width:70px;
    font-size: .6rem;
  }
  .time-line-div>p:nth-child(2){
    position:absolute;
    left: 54px;
    width:12px;
    height:12px;
    top:10px;
    background:#5CB85C;
    border-radius: 50%;
    z-index: 3;
  }
  .line-top {
    position:absolute;
    width: 5px;
    height: 80px;
    top: 13px;
    left: 59px;
    border-left: 2px solid #cdcdcd;
    z-index: 1;
  }
  .time-line-div>p:nth-child(3){
    position:absolute;
    left: 70px;
    padding: 3px;
    background: #fff;
    font-size:.6rem;
    text-align: left;
    color:#000;
    border-radius: 10px;
    border: 1px solid #ddd;
  }

  .time-line-detail>p{
    margin-left: 30px;
    margin-bottom: 10px;
  }
</style>
